package com.naizhuai.ui.user.userinfo;


import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.naizhuai.AppContext;
import com.naizhuai.MainActivity;
import com.naizhuai.Model.AccountHelper;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.BaseFragment;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.ui.entity.Bus.Bus;
import com.naizhuai.ui.entity.QRCodeMsgBean;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.ui.entity.setting.UserAbilityLabels;
import com.naizhuai.ui.management.CompanyTotalStructureActivity;
import com.naizhuai.ui.mianbusiness.setting.ManageCreateQRCodeActivity;
import com.naizhuai.ui.mianbusiness.setting.PersonRadarActivity;
import com.naizhuai.ui.rank.RankActivity;
import com.naizhuai.ui.testunit.ManageTestCreateQRCodeActivity;
import com.naizhuai.ui.user.InfoSettingActivity;
import com.naizhuai.ui.user.multtype.AchieveMentViewBinder;
import com.naizhuai.ui.user.multtype.PersonInfo;
import com.naizhuai.ui.user.multtype.PersonInfoViewBinder;
import com.naizhuai.ui.user.multtype.Space;
import com.naizhuai.ui.user.multtype.SpaceViewBinder;
import com.naizhuai.util.HideNumberUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.NotifyUtil;
import com.naizhuai.util.RxBus;
import com.naizhuai.util.ViewUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.functions.Action1;


public class InfoFragment extends BaseFragment implements InfoContract.View, AchieveMentViewBinder.ClickCallback {
    Unbinder unbinder;
    @BindView(R.id.person_setting)
    RecyclerView personSetting;
    MultiTypeAdapter mTypeAdapter;
    Items mItems;
    PersonUserBean mUserBean;
    @BindView(R.id.user_thumb)
    CircleImageView userThumb;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.user_level)
    TextView userLevel;
    @BindView(R.id.level_process_back)
    ImageView levelProcessBack;
    @BindView(R.id.level_process_content)
    ImageView levelProcessContent;
    @BindView(R.id.progress_text)
    TextView progressText;
    private InfoContract.Presenter mInfoPresenter;
    private  boolean isReceive;
    private MainActivity mMainActivity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mMainActivity=(MainActivity)context;
    }

    public InfoFragment() {
        // Required empty public constructor
    }

    public static InfoFragment newInstance() {
        InfoFragment fragment = new InfoFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_info, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        InitView();
        InitPresenter();
        InitEvent();

    }

    private void InitEvent() {
        RxBus.getDefault().toObservableSticky(Bus.UserThumb.class)
                .subscribe(new Action1<Bus.UserThumb>() {
                    @Override
                    public void call(Bus.UserThumb thumb) {
                        ViewUtils.showRoundImg(thumb.userlogo,userThumb);
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        isReceive=true;
        RxBus.getDefault().toObservableSticky(Bus.UserChange.class)
                .subscribe(new Action1<Bus.UserChange>() {
                    @Override
                    public void call(Bus.UserChange userChange) {
                        if (isReceive){
                            decrementcount();
                            mInfoPresenter.populateUserInfo();
                            if (getcount()==0){
                                 RxBus.getDefault().removeStickEvent(Bus.UserChange.class);
                                 reset();
                            }
                        }
                    }
                });

    }

    private void InitPresenter() {
        mInfoPresenter = new InfoPresenter(AccountHelper.getUid());
        mInfoPresenter.takeView(this);
        mInfoPresenter.populateUserInfo();
    }

    private void InitView() {
        mTypeAdapter = new MultiTypeAdapter();

        mTypeAdapter.register(String.class, new AchieveMentViewBinder(this));

        mTypeAdapter.register(Space.class, new SpaceViewBinder());

        mTypeAdapter.register(PersonInfo.class, new PersonInfoViewBinder());

        personSetting.setLayoutManager(new LinearLayoutManager(getActivity()));

        mTypeAdapter.setItems(mItems = new Items());

        personSetting.setAdapter(mTypeAdapter);

    }

    @Override
    public void clickRader() {
        if (getActivity() instanceof BaseActivity) {
            BaseActivity activity = (BaseActivity) getActivity();
            Intent intent = new Intent(activity, PersonRadarActivity.class);
            intent.putExtra(PersonUserBean.USER_ID_KEY, AccountHelper.getUid());
            activity.startActivityTransition(intent);
        }
    }

    @Override
    public void clickOrganization() {
        IntentUtils.startActivity(getActivity(), CompanyTotalStructureActivity.class);
    }

    @Override
    public void clickRank() {
//        RankActivity.start(getActivity());
        shortToast(getString(R.string.function_in_the_development));
    }

    private void configView(PersonUserBean user) {
        mItems.clear();
        mItems.add("AchieveMent");

        mItems.add(new Space(10));

        boolean isComPany = TextUtils.isEmpty(user.getCompanyId());
        mItems.add(new PersonInfo(R.drawable.my_company, getString(R.string.my_company), user.getCompanyName(), !isComPany, () -> {
            //ComPanyQrcode
            if (!isComPany) {
                 generateComPanyQrCode(user);
            }else {
                mMainActivity.openScanQrCode();
            }
        }));

        boolean isDepartment = TextUtils.isEmpty(user.getDepartmentId());

        mItems.add(new PersonInfo(R.drawable.my_department, getString(R.string.my_department), user.getDepartmentName(), !isDepartment, () -> {
            if (!isDepartment) {
                generateDepartedQrCode(user);
            }else {
                mMainActivity.openScanQrCode();
            }
        }));

        mItems.add(new PersonInfo(R.drawable.my_phone, getString(R.string.my_phone), user.getPhoneNumber(), () -> {

        }));

        mItems.add(new PersonInfo(R.drawable.my_email, getString(R.string.my_email), user.getEmail(), () -> {

        }));

        mItems.add(new Space(5));

        mItems.add(new PersonInfo(R.drawable.my_qrcode, getString(R.string.my_qrcode), true, () -> {
            //MyQrcode
            generateMyQrCode(user);
        }));

        mItems.add(new Space(20));

        mItems.add(new PersonInfo(R.drawable.my_setting, getString(R.string.my_setting), true, () -> {
            InfoSettingActivity.start(getActivity());
        }));

        mTypeAdapter.notifyDataSetChanged();

    }

    @Override
    public void onPause() {
        super.onPause();
        isReceive=false;
    }

    private void generateMyQrCode(PersonUserBean user) {
        QRCodeMsgBean bean = new QRCodeMsgBean();
        bean.setScanType(QRCodeMsgBean.USER_JOIN_TYPE);
        QRCodeMsgBean.PersonMsg person = new QRCodeMsgBean.PersonMsg();
        person.setUserId(user.getUid());
        person.setUserName(user.getName());
        person.setUserPhoneNumber(HideNumberUtils.hidePhoneNumber(user.getPhoneNumber()));
        person.setUserThumb(user.getUserLogoUrl());
        bean.setPerson(person);
        startScanQrCode(bean);
    }

    private void generateDepartedQrCode(PersonUserBean user) {
        QRCodeMsgBean bean = new QRCodeMsgBean();
        bean.setScanType(QRCodeMsgBean.DEPARTMENT_JOIN_TYPE);
        QRCodeMsgBean.GroupMsg group = new QRCodeMsgBean.GroupMsg();
        group.setDepartName(user.getDepartmentName());
        group.setCompanyId(user.getCompanyId());
        group.setDepartId(user.getDepartmentId());
        bean.setGroup(group);
        startScanQrCode(bean);

    }

    private void generateComPanyQrCode(PersonUserBean user) {
        QRCodeMsgBean bean = new QRCodeMsgBean();
        bean.setScanType(QRCodeMsgBean.COMPANY_JOIN_TYPE);
        QRCodeMsgBean.GroupMsg group = new QRCodeMsgBean.GroupMsg();
        group.setCompanyId(user.getCompanyId());
        group.setCompanyName(user.getCompanyName());
        bean.setGroup(group);
        startScanQrCode(bean);
    }

    private void startScanQrCode(QRCodeMsgBean bean) {
        IntentUtils.startActivityWithObject(QRCodeMsgBean.QRCode_MSG_KEY, bean, getActivity(), ManageCreateQRCodeActivity.class);
    }

    @Override
    public void showUserInfo(PersonUserBean user) {
        this.mUserBean = user;
        configView(user);
    }

    @Override
    public void showTitleHeader(UserAbilityLabels userAbilityLabels) {
        ViewUtils.showRoundImg(userAbilityLabels.getUserThumb(),userThumb);
        userName.setText(userAbilityLabels.getUsername());
        userLevel.setText(String.format("LV%1$s", userAbilityLabels.getUserlevel()));
        progressText.setText(String.format("%1$s/%2$s", userAbilityLabels.getExperience(), userAbilityLabels.getTotalExperience()));
        initActionProcess(Float.parseFloat(userAbilityLabels.getExperience()) / Float.parseFloat(userAbilityLabels.getTotalExperience()));
    }

    @Override
    public void userDataError() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
    private void initActionProcess(float radius) {
        levelProcessBack.post(() -> {
            int totalWidth = levelProcessBack.getWidth();
            int proTotalWidth = (int) (totalWidth * radius);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) levelProcessContent.getLayoutParams();
            params.width = proTotalWidth;
            levelProcessContent.setLayoutParams(params);
        });
    }
}
